package com.lsa.letcode.the59.spiralMatrix2;

public class Solution {
    public int[][] generateMatrix(int n) {
        if (n < 0){
        	return null;
        }

        int[][] matrix = new int[n][n];
        if (n == 0){
        	return matrix;
        }
        
        int r = n;
        int c = n;
        
        int cnt = r * c;
        
        int walked = 1;
        
        int x = 0;
        int y = 0;
        
        int origX = 0;
        int origY = 0;
        
        while(walked <= cnt) {
        	matrix[x][y] = walked;
        	
        	if (x - origX == 0 && y - origY < c - 1) {
        		y++;
        	}
        	else if (y - origY == c - 1 && x - origX < r - 1) {
        		x++;
        	}
        	else if (x - origX == r - 1 && y - origY > 0) {
        		y--;
        	}
        	else if (x - origX > 1) { //y - origY == 0{
        		x--;
        	}
        	else { //y - origY == 0 && x - origX == 1 -> change matrix size and origin
        		y++;
        		r -= 2;
        		c -= 2;
        		origX++;
        		origY++;
        	}
        	
        	++walked;
        }
        
        return matrix;
    }
}